import QQMapWX from '@/lib/qqmap-wx-jssdk';
import useModal from '@/hooks/useModal';
const { VITE_TENCENT_MAP_KEY } = import.meta.env;
const { showModal } = useModal();
const qqmapsdk = new QQMapWX({
  key: VITE_TENCENT_MAP_KEY,
});

class Location {
  /**
   * 检查是否拥有位置权限
   * @returns Promise<boolean> 是否已授权
   */
  private static async checkAuthorization(): Promise<boolean> {
    return new Promise((resolve) => {
      uni.getSetting({
        success: (res) => {
          resolve(res.authSetting['scope.userLocation']);
        },
        fail: () => {
          resolve(false); // 如果失败，默认未授权
        },
      });
    });
  }

  /**
   * 请求获取位置权限
   * @returns Promise<boolean> 请求是否成功
   */
  private static async requestAuthorization(): Promise<boolean> {
    return new Promise((resolve) => {
      uni.authorize({
        scope: 'scope.userLocation',
        showClose: true,
        success: () => {
          resolve(true);
        },
        fail: () => {
          showModal(
            '需要获取您的地理位置，请前往设置中授权',
            {
              success: (res) => {
                if (res.confirm) {
                  uni.openSetting();
                }
              },
            },
            '请求授权位置权限',
          );
          resolve(false);
        },
      });
    });
  }

  /**
   * 获取用户所在经纬度信息
   * @returns Promise<UniApp.GetLocationSuccessCallbackResult> 位置信息
   */
  private static async getLocation(): Promise<UniApp.GetLocationSuccess> {
    return new Promise((resolve, reject) => {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => resolve(res),
        fail: (err) => reject(err),
      });
    });
  }

  /**
   * 使用腾讯地图sdk获取用户详细位置
   * @returns Promise<UniApp.GetLocationSuccessCallbackResult> 位置信息
   */
  private static async getDetailedLocation(location?: { lat: number; lng: number }): Promise<IReverseGeocoderType> {
    return new Promise((resolve, reject) => {
      qqmapsdk.reverseGeocoder({
        location: location ? `${location.lat},${location.lng}` : undefined,
        success: (res: any) => resolve(res.result),
        fail: () => reject(),
      });
    });
  }

  /**
   * 检查权限并获取经纬度uni.getLocatio API
   * @returns Promise<UniApp.GetLocationSuccess | null> 位置信息或 null
   */
  public static async positioningLatitudeLongitude(): Promise<UniApp.GetLocationSuccess | null> {
    try {
      const isAuthorized = await this.checkAuthorization();

      if (!isAuthorized) {
        const authorized = await this.requestAuthorization();
        if (!authorized) {
          return null;
        }
      }

      return await this.getLocation();
    } catch (error) {
      console.error('获取位置信息失败:', error);
      return null;
    }
  }

  /**
   * 检查权限并获取经纬度 腾讯地图API
   * @param location 经纬度信息，默认当前位置
   * @returns Promise<UniApp.GetLocationSuccess | null> 位置信息或 null
   */
  public static async reverseGeocoderLocation(location?: { lat: number; lng: number }): Promise<IReverseGeocoderType | null> {
    try {
      const isAuthorized = await this.checkAuthorization();
      if (!isAuthorized) {
        const authorized = await this.requestAuthorization();
        if (!authorized) {
          return null;
        }
      }

      return await this.getDetailedLocation(location);
    } catch (error) {
      console.error('获取位置信息失败:', error);
      return null;
    }
  }
}

export default Location;
